import os
from openai import OpenAI
from init import init
from imgPreProcess import imgPreProcess
import sys
import subprocess

init()

class Vision:
    def __init__(self):
        self.client = OpenAI(
            base_url=os.environ.get("BASE_URL"),
            api_key=os.environ.get("API_KEY"),
        )
        self.__img__ = None
        # server = subprocess.Popen(["cpolar", "http", "8081"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        # self.__url__ = server.stdout.readline()
        # while not "https" in self.__url__ and server.poll() == None: self.__url__ = server.stdout.readline()
        # self.__url__ = self.__url__[self.__url__.index("https"):]
        # print(self.__url__)
        # check=input("url是否合理？")
        # if check=="n":
        #     sys.exit(1)
        self.__url__ = "https://769a11b1.r34.cpolar.top"
        
    def setImg(self, img):
        self.__img__ = img
        if not os.path.exists(os.path.join("img", self.__img__)):
            print(f"图片{self.__img__}不存在")
            sys.exit(1)
        imgPreProcess(self.__img__, 1)

    def chat(self, message:str) -> str:
        response = self.client.chat.completions.create(
            model=os.environ.get("VISION"),
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "你在这张图片中看到了什么？"},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"{self.__url__}/img/{self.__img__}"
                            },
                        },
                    ],
                }
            ],
        )
        return response.choices[0].message.content